//
//  GMArtworkViewController.m
//  gentleman
//
//  Created by 范月成 on 2017/12/6.
//  Copyright © 2017年 fancy. All rights reserved.
//

#import "GMArtworkViewController.h"
#import "GMGallery.h"
#import "GMArtworkInfoHeader.h"
#import "GMArtworkInfoView.h"
#import "GMPlaceHolderView.h"
#import "GMCommentCell.h"
#import "GMDownloader.h"

#define kPageMenuH  40
#define kHeaderH    200
@interface GMArtworkViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong, readwrite) GMArtwork *artwork;
@property (nonatomic, strong) GMGallery *gallery;

@property (nonatomic, strong) UIScrollView *contentView;
@property (nonatomic, strong) UISegmentedControl *segmentedControl;
@property (nonatomic, strong) GMArtworkInfoHeader *header;
@property (nonatomic, strong) GMArtworkInfoView *info;
@property (nonatomic, strong) UITableView *commentList;
@property (nonatomic, strong) GMPlaceHolderView *commentEmpty;
@property (nonatomic, strong) UIButton *likeButton;

@end

@implementation GMArtworkViewController

+ (void)load {
    [MGJRouter registerURLPattern:kRouterArtworkDetail
                        toHandler:^(NSDictionary *routerParameters) {
                            GMArtwork *artwork = routerParameters[MGJRouterParameterUserInfo][@"artwork"];
                            GMArtworkViewController *artworkDetail = [[GMArtworkViewController alloc] initWithArtwork:artwork];
                            artworkDetail.hidesBottomBarWhenPushed = YES;
                            
                            [[UIViewController currentNavigationViewController] pushViewController:artworkDetail animated:YES];
                        }];
}

- (instancetype)initWithArtwork:(GMArtwork *)artwork {
    if (self = [super init]) {
        self.artwork = artwork;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = self.artwork.title;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.likeButton];
 
    GMArtwork *art = [GMArtwork objectForId:@(self.artwork.gid)];
    self.likeButton.selected = art.isLike;
    
    [self requestDatas];
}

- (void)requestDatas {
    @weakify(self)
    [GMGallery getWithArtworkUrl:self.artwork.url completed:^(NSError *error, GMGallery *gallery) {
        @strongify(self)
        if (error) {
            self.info.refreshButton.hidden = NO;
            self.commentEmpty.refreshButton.hidden = NO;
            self.commentEmpty.title = error.domain;
            [GMUIHelper alertWithTitle:error.domain message:nil];
        } else {
            self.gallery = gallery;
            [self.header setHandelButtonsEnable:YES];
            [self.info configUIWithArtwork:self.artwork gallery:self.gallery];
            [self.commentList reloadData];
        }
    }];
}

- (void)initSubviews {
    [super initSubviews];
    
    [self.view addSubview:self.header];
    [self.view addSubview:self.segmentedControl];
    [self.view addSubview:self.contentView];
    [self.contentView addSubview:self.info];
    [self.contentView addSubview:self.commentList];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    [self.header mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kScreenWidth);
        make.height.mas_equalTo(kHeaderH);
        make.left.equalTo(self.view);
        make.top.equalTo(self.view).offset(self.safeAreaTop);
    }];
    
    [self.segmentedControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kScreenWidth-40);
        make.height.mas_equalTo(30);
        make.left.equalTo(self.view).offset(20);
        make.top.equalTo(self.header.mas_bottom).offset(5);
    }];
    
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kScreenWidth);
        make.height.mas_equalTo(kScreenHeight-self.safeAreaTop-kHeaderH-40-self.safeAreaBottom);
        make.left.equalTo(self.view);
        make.top.equalTo(self.segmentedControl.mas_bottom).offset(5);
    }];
    
    [self.info mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kScreenWidth);
        make.height.equalTo(self.contentView.mas_height);
        make.left.equalTo(self.contentView);
        make.top.equalTo(self.contentView);
    }];
    
    [self.commentList mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kScreenWidth);
        make.height.equalTo(self.contentView.mas_height);
        make.left.equalTo(self.info.mas_right);
        make.top.equalTo(self.contentView);
    }];
}

#pragma mark - scrollview
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if ([scrollView isEqual:self.contentView]) {
        self.segmentedControl.selectedSegmentIndex = scrollView.contentOffset.x/kScreenWidth;
    }
}

#pragma mark - Action
- (void)changeAction:(UISegmentedControl *)sender {
    NSInteger index = sender.selectedSegmentIndex;
    [self.contentView setContentOffset:CGPointMake(kScreenWidth*index, 0) animated:YES];
}

- (void)like:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        self.artwork.isLike = YES;
        [self.artwork save];
    } else {
        GMArtwork *artwork = [GMArtwork objectForId:@(self.artwork.gid)];
        if (artwork.isDownload) {
            artwork.isLike = NO;
            [artwork save];
        } else {
            [self.artwork deleteObject];
        }

        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationReloadList object:nil];
    }
}

#pragma mark - table view
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.gallery.comments.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GMCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GMCommentCell" forIndexPath:indexPath];
    [self configureCell:cell atIndexPath:indexPath];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [tableView fd_heightForCellWithIdentifier:@"GMCommentCell" cacheByIndexPath:indexPath configuration:^(GMCommentCell *cell) {
        [self configureCell:cell atIndexPath:indexPath];
    }];
}

- (void)configureCell:(GMCommentCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = YES;
    cell.comment = self.gallery.comments[indexPath.row];
}

#pragma mark - getter

- (GMArtworkInfoHeader *)header {
    if (!_header) {
        _header = [[GMArtworkInfoHeader alloc] init];
        _header.artwork = self.artwork;
        @weakify(self)
        _header.readBlock = ^{
            @strongify(self)
            [MGJRouter openURL:kRouterArtworkBrowser
                  withUserInfo:@{
                               @"artwork": self.artwork,
                               @"gallery": self.gallery}
                    completion:nil];
        };
        
        _header.downloadBlock = ^(UIButton *sender, BOOL isDownload) {
            @strongify(self)
            if (isDownload) {
                [MGJRouter openURL:kRouterDownloadList withUserInfo:@{@"artwork":self.artwork} completion:nil];
            } else {
                sender.enabled = NO;
                GMDownloader *downloader = [GMDownloader defaultDownloader];
                [downloader downloadArtworksWithArtwork:self.artwork gallery:self.gallery progress:^(NSInteger receivedCount, NSInteger expectedCount) {
                    dispatch_async_on_main_queue(^{
                        [sender setTitle:[NSString stringWithFormat:@"%ld/%ld", receivedCount, expectedCount] forState:UIControlStateNormal];
                    });
                } completed:^(NSError *error, NSInteger receivedCount, NSInteger expectedCount) {
                    if (error) {
                        dispatch_async_on_main_queue(^{
                            [sender setTitle:error.domain forState:UIControlStateNormal];
                        });
                    } else {//提示
                        self.header.artwork = self.artwork;
            
                        [GMUIHelper alertWithTitle:@"提示" message:[NSString stringWithFormat:@"一共%ld张，成功下载%ld张", expectedCount, receivedCount] ensure:^{
                            [MGJRouter openURL:kRouterDownloadList withUserInfo:@{@"artwork":self.artwork} completion:nil];
                        } cancel:nil];
                    }
                }];
            }
        };
        
        _header.categoryTapBlock = ^(NSString *category) {
            [MGJRouter openURL:[MGJRouter generateURLWithPattern:kRouterArtworkList parameters:@[@"2", category]]];
        };
        
        _header.thumbTapBlock = ^(UIImageView *view) {
            @strongify(self)
            YYPhotoGroupItem *item = [YYPhotoGroupItem new];
            item.thumbView = view;
            item.largeImageURL = [NSURL URLWithString:self.artwork.thumb];
            YYPhotoGroupView *photoGroup = [[YYPhotoGroupView alloc] initWithGroupItems:@[item]];
            [photoGroup presentFromImageView:view toContainer:self.navigationController.view animated:YES completion:nil];
        };
        
        _header.torrentBlock = ^{
            @strongify(self)
            [MGJRouter openURL:kRouterTorrentList withUserInfo:@{@"artwork":self.artwork} completion:nil];
        };
    }
    return _header;
}

- (UIScrollView *)contentView {
    if (!_contentView) {
        _contentView = [[UIScrollView alloc] init];
        _contentView.delegate = self;
        _contentView.pagingEnabled = YES;
        _contentView.showsVerticalScrollIndicator = NO;
        _contentView.showsHorizontalScrollIndicator = NO;
        _contentView.contentSize = CGSizeMake(kScreenWidth*2, 0);
        _contentView.backgroundColor = [UIColor whiteColor];
    }
    return _contentView;
}

- (UISegmentedControl *)segmentedControl {
    if (!_segmentedControl) {
        _segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"详情", @"评论"]];
        _segmentedControl.selectedSegmentIndex = 0;
        [_segmentedControl addTarget:self action:@selector(changeAction:) forControlEvents:UIControlEventValueChanged];
    }
    return _segmentedControl;
}

- (GMArtworkInfoView *)info {
    if (!_info) {
        _info = [[GMArtworkInfoView alloc] init];
        @weakify(self)
        _info.tagTapBlock = ^(NSString *tag) {
            [MGJRouter openURL:[MGJRouter generateURLWithPattern:kRouterArtworkList parameters:@[@"3", tag]]];
        };
        
        _info.refreshBlock = ^{
            @strongify(self)
            [self requestDatas];
        };
        
        _info.thumbTapBlock = ^(UIImageView *view) {
            @strongify(self)
            YYPhotoGroupItem *item = [YYPhotoGroupItem new];
            item.thumbView = view;
            item.largeImageURL = [NSURL URLWithString:self.gallery.thumbnail];
            YYPhotoGroupView *photoGroup = [[YYPhotoGroupView alloc] initWithGroupItems:@[item]];
            [photoGroup presentFromImageView:view toContainer:self.navigationController.view animated:YES completion:nil];
        };
        
        _info.similarArtBlock = ^{
            @strongify(self)
            NSString *searchKey = [self.artwork.title handleString];
            
            if (![searchKey isNotBlank]) {
                //无类似
                [GMUIHelper alertWithTitle:@"木有类似画廊" message:nil];
                return;
            }
            [MGJRouter openURL:[MGJRouter generateURLWithPattern:kRouterArtworkList parameters:@[@"1", searchKey]] withUserInfo:@{@"hidden":@1} completion:nil];
        };
        
        _info.otherUploadBlock = ^{
            @strongify(self)
            [MGJRouter openURL:[MGJRouter generateURLWithPattern:kRouterArtworkList parameters:@[@"4", self.artwork.uploader]]];
            
        };
    }
    return _info;
}

- (UITableView *)commentList {
    if (!_commentList) {
        _commentList = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _commentList.delegate = self;
        _commentList.dataSource = self;
        [_commentList disabledEstimatedHeight];
        _commentList.tableFooterView = [UIView new];
        [_commentList registerClass:GMCommentCell.class forCellReuseIdentifier:@"GMCommentCell"];
        @weakify(self)
        [_commentList gm_configureWithPlaceHolderBlock:^UIView * _Nonnull(UITableView * _Nonnull sender) {
            @strongify(self)
            return self.commentEmpty;
        } normalBlock:nil];
    }
    return _commentList;
}

- (GMPlaceHolderView *)commentEmpty {
    if (!_commentEmpty) {
        _commentEmpty = [[GMPlaceHolderView alloc] initWithFrame:self.commentList.bounds];
        _commentEmpty.title = @"木有任何评论";
        _commentEmpty.refreshButton.hidden = YES;
        @weakify(self)
        _commentEmpty.refreshBlock = ^{
            @strongify(self)
            [self requestDatas];
        };
    }
    return _commentEmpty;
}

- (UIButton *)likeButton {
    if (!_likeButton) {
        _likeButton = [[UIButton alloc] init];
        [_likeButton setImage:kImage(@"unlike") forState:UIControlStateNormal];
        [_likeButton setImage:kImage(@"like") forState:UIControlStateSelected];
        [_likeButton addTarget:self action:@selector(like:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _likeButton;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
